package com.sunday.haowushop.ui.main;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.IndexViewPager;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.Member;
import com.sunday.haowushop.entity.ProductClassify;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.ui.index.BrandFragment;
import com.sunday.haowushop.ui.index.GlobalBuyFragment;
import com.sunday.haowushop.ui.index.TodayFragment;
import com.sunday.haowushop.ui.mine.customer.CustomerListActivity;
import com.sunday.haowushop.ui.product.SearchProductActivity;
import com.sunday.haowushop.ui.product.SearchProductListActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/4/11.
 */

public class IndexFragment extends BaseFragment {

    @Bind(R.id.menu)
    ImageView menu;
    @Bind(R.id.index_circle_img)
    CircleImageView indexCircleImg;
    @Bind(R.id.index_shop_name)
    TextView indexShopName;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.appbar_layout)
    AppBarLayout appbarLayout;
    @Bind(R.id.view_pager)
    IndexViewPager viewPager;


    private List<String> titles = new ArrayList<>();
    private List<ProductClassify> productClassifyList = new ArrayList<>();
    private Member member;

    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        member = BaseApp.getInstance().getMember();
        initView();
    }

    private void initView() {
        titles.clear();
        titles.add("今日特卖");
        titles.add("品牌团");
        titles.add("跨境商城");
        //titles.add("试用中心");
        getTabTitles();
        indexShopName.setText(String.valueOf(member.getMemberCount()));

    }


    public void getMemberInfo() {
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().getMemberInfo(BaseApp.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() != null)
                        member = response.body().getResult();
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    BaseApp.getInstance().setMember(member);
                    indexShopName.setText(String.valueOf(member.getMemberCount()));
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    private void getTabTitles() {
        Call<ResultDO<List<ProductClassify>>> call = ApiClient.getApiAdapter().getProCat();
        call.enqueue(new Callback<ResultDO<List<ProductClassify>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<ProductClassify>>> call, Response<ResultDO<List<ProductClassify>>> response) {
                if (isFinish) {
                    return;
                }
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    for (ProductClassify item : response.body().getResult()) {
                        titles.add(item.getName());
                    }
                    productClassifyList.clear();
                    productClassifyList.addAll(response.body().getResult());
                    initFragment();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<ProductClassify>>> call, Throwable t) {

            }
        });

    }


    private void initFragment() {
        viewPager.setAdapter(new IndexViewPagerAdapter(getChildFragmentManager()));
        viewPager.setOffscreenPageLimit(titles.size() + 2);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOnCheckCanScrollListener(new IndexViewPager.OnCheckCanScrollListener() {
            @Override
            public boolean isCanScroll() {
                return !checkTabLayoutVisible();
            }
        });

    }

    public class IndexViewPagerAdapter extends FragmentPagerAdapter {

        private Fragment[] fragments;

        public IndexViewPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[titles.size()];
        }

        @Override
        public Fragment getItem(int position) {
            if (fragments[position] == null) {
                if (position == 0) {
                    fragments[position] = TodayFragment.newInstance();
                } else if (position == 1) {
                    fragments[position] = BrandFragment.newInstance();
                } else if (position == 2) {
                    fragments[position] = GlobalBuyFragment.newInstance();
                } else {
                    fragments[position] = IndexClasssifyFragment.newInstance(productClassifyList.get(position - 3).getId(), productClassifyList.get(position - 3).getName());
                }
            }
            return fragments[position];
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.index_circle_img, R.id.index_shop_name})
    void onClick() {
        intent = new Intent(mContext, CustomerListActivity.class);
        intent.putExtra("showVip", true);
        startActivity(intent);
    }

    @OnClick(R.id.layout_search)
    void onClick1() {
        intent = new Intent(mContext, SearchProductListActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.menu)
    void onClick2() {
        intent = new Intent(mContext, SearchProductActivity.class);
        startActivity(intent);
    }


    public boolean checkTabLayoutVisible() {
        boolean cover = false;
        Rect rect = new Rect();
        cover = tabLayout.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= tabLayout.getMeasuredWidth() && rect.height() >= tabLayout.getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }


}
